package com.swd2010.mobileSearch.network;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;


public class AutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
	
    private ArrayList<String> resultList;
    
    /**
    public PlacesAutoCompleteAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }
    **/
    
    /**
	 * @param context
	 * @param resource
	 * @param textViewResourceId
	 * @param objects
	 */
	public AutoCompleteAdapter(Context context, int resource,
			int textViewResourceId, List<String> objects) {
		
		super(context, resource, textViewResourceId, objects);
		
		this.resultList = (ArrayList<String>) objects;
		
	}

	
	
	@Override
    public int getCount() {
        return resultList.size();
    }

    @Override
    public String getItem(int index) {
        return resultList.get(index);
    }

    @Override
    public Filter getFilter() {
    	
        Filter filter = new Filter() {
        	
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
            	
                FilterResults filterResults = new FilterResults();
                
                ConnectInformation conInformation = new ConnectInformation();
                
                
                if (constraint != null) {
                	


// http://localhost:8080/SearchServer/REST/search/PersonAutocomplete?searchTerm=ha&numResults=4
                	
                	resultList = PersonSearchAutoCompleteWebservice.autocomplete( conInformation.getPersonAutoCompleteUrl(constraint.toString()) );
                	
                	
                    // Assign the data to the FilterResults
                    filterResults.values = resultList;
                    filterResults.count = resultList.size();
                    
                }
                
                return filterResults;
            }

            
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
            	
                if (results != null && results.count > 0) {
                    notifyDataSetChanged();
                }
                else {
                    notifyDataSetInvalidated();
                }
                
            }
            
            };
            
        return filter;
        
    }
    
}
